import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Table, Divider } from 'antd';
import Form from './RecordForm';

export interface IProps {
  dispatch?: ({ type }: { type: string, payload?: any }) => Promise<any>;
  children?: React.ReactNode;
  loading?: boolean;
  buttons?: Array<any>;
  history?: any;
  record: {
    id: string;
    port: string;
    station: string;
    name: string;
    chargingPortNumber: string;
  };
  cond?: any;
  list?: {
    data: Array<any>;
    dataCnt: number;
  };
}


@connect(({ analyse_charge, menu }) => ({
  list: analyse_charge.recordList || {},
  cond: analyse_charge.recordCond || {},
  buttons: menu.buttons,
}))
class Record extends Component<IProps, any> {

  state = {
    current: 0,
  }

  queryData(params) {
    const { dispatch } = this.props;

    dispatch({
      type: 'analyse_charge/updateRecordCond',
      payload: params
    });
  }

  initCurrent = () => {
    this.setState({
      current: 0
    })
  }

  componentDidMount() {
    const { dispatch, record } = this.props;
    const params = {
      deviceId: record.id,
      port: record.chargingPortNumber,
      pageSize: 10,
      pageNum: 1
    }

    dispatch({
      type: 'analyse_charge/updateRecordCond',
      payload: params
    })
  }

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond } = this.props;
    cond.pageSize = pageSize;
    dispatch({ type: `analyse_charge/updateRecordCond`, payload: cond })
  }

  render() {
    const { list, buttons, record } = this.props;
    const { data = [], dataCnt = 0 } = list;

    const btnList = {};
    if (Array.isArray(buttons)) {
      buttons.forEach(item => {
        btnList[item.name] = item.name
      });
    }

    const columns = [
      {
        title: '断电时间',
        dataIndex: 'powerFailureTime',
        key: 'powerFailureTime'
      },
      {
        title: '断电原因',
        dataIndex: 'reason',
        key: 'reason',
      },
    ];

    const ans = Array.isArray(data) ? data.map((it, index) => ({
      key: index,
      ...it,
    })) : []

    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      current: this.state.current,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      onChange: (current) => {
        this.setState({ current }, () => this.queryData({ pageNum: current }));
      },
    };

    return (
      <div>
        <Form current={this.state.current} initCurrent={this.initCurrent} new={!!btnList['新增']} />
        <Table
          columns={columns}
          dataSource={ans}
          indentSize={60}
          loading={this.props.loading}
          pagination={pagination}
          bordered
        />
      </div>
    );
  }
}

export default Record;
